package com.minelx.datamicroscope;

import com.minelx.statementsplus.cha.base.ChaSession;
import com.minelx.statementsplus.cha.base.HttpChaSession;
import com.minelx.statementsplus.cha.base.TunnelChaSession;
import io.gitee.minelx.commontools.multithread.processcontrol.SemaphoreHelper;

import javax.sql.DataSource;
import java.util.concurrent.atomic.AtomicLong;

public class ChaSessionFactory {
	private static final AtomicLong TIME = new AtomicLong(-1);

	private static final int EXPIRING_MINUS = 30;

	private static final int EXPIRING_SECONDS = 60 * EXPIRING_MINUS;

	private static final int PERMITS = 3 /* permits released once. */;

	private static final int PERMITS_RELEASING_INTERVAL = 1000 /* ms */;

	private static ChaSession INSTANCE = null;

	public static ChaSession configured() {
		if (TIME.get() == -1) {
			return reorder();
		}
		if ((System.currentTimeMillis() - TIME.get()) > (EXPIRING_SECONDS * 1000)) {
			return reorder();
		}
		return INSTANCE;
	}

	private static ChaSession reorder() {
		TIME.set(System.currentTimeMillis());
		INSTANCE = reorderInstance();
		return INSTANCE;
	}

	private static ChaSession reorderInstance() {
		System.out.println("ChaSessionFactory.static initializer :: creating instance of \"com.minelx.statementsplus.cha.base.HttpChaSession\"...");
		return HttpChaSession.login("zyh", "123456",
				SemaphoreHelper.limit(PERMITS, PERMITS_RELEASING_INTERVAL));
	}

	public static ChaSession tunnel(DataSource dataSource) {
		return new TunnelChaSession(dataSource);
	}
}
